import request from "../../../utils/request";
import PubSub from 'pubsub-js';
import moment from "moment";

const app = getApp();

Page({
    data: {
        isPlay: false,
        song: {},
        currentTime: '00:00',  //当前播放时间
        durationTime: '00:00', //音乐总时长
        ratio: '0%', //当前播放进度比例
    },

    onLoad: function (options) {
        this.songID = parseInt(options.songID);
        this.getSong();
        this.bindListeners();
        //进入的和正在播放的是同一首歌则直接播放
        const {isMusicPlay, musicId} = app.globalData;
        if (this.songID === musicId && isMusicPlay) {
            this.setData({isPlay: true});
            this.musicControll(true);
        }
        //订阅：获取从每日推荐页面传递过来的songID----订阅操作放到这里，需要在onUnload里取消订阅
        this.token = PubSub.subscribe('musicId', (msg, data) => {
            this.songID = data.songID;
            this.getSong();
            this.musicControll(true);
        });
    },

    async getSong() {
        const res = await request('/song/detail', {ids: this.songID});
        const song = res.songs[0];
        song.songer = song.ar.map(v => v.name).join('&');
        const durationTime = moment(song.dt).format('mm:ss');
        this.setData({song, durationTime});
        //设置navigationBar上的标题
        wx.setNavigationBarTitle({
            title: song.name
        });
    },

    handlePlay() {
        const {isPlay} = this.data;
        this.setData({isPlay: !isPlay});
        this.musicControll(this.data.isPlay);
    },

    //控制音乐播放/暂停的功能函数
    async musicControll(isPlay) {
        if (!this.audioManager) {
            this.audioManager = wx.getBackgroundAudioManager();
        }
        if (isPlay) {
            if (!this.musicLink) {
                //获取音乐播放链接
                const res = await request('/song/url', {id: this.songID});
                this.musicLink = res.data[0].url;
            }
            //创建音乐播放器的实例
            this.audioManager.src = this.musicLink;
            this.audioManager.title = this.data.song.name;
            this.audioManager.play();
        } else {
            this.audioManager.pause();
        }
    },

    //各种监听事件
    /*
    * 问题： 如果用户操作系统的控制音乐播放/暂停的按钮，页面不知道，导致页面显示是否播放的状态和
    *       真实的音乐播放状态不一致.
    * 解决方案：
    *   1. 通过控制音频的实例 backgroundAudioManager 去监视音乐播放/暂停
    * */
    bindListeners() {
        this.audioManager = wx.getBackgroundAudioManager();
        this.audioManager.onPlay(() => {
            app.globalData.musicId = this.songID;
            this.changePlayState(true);
        });
        this.audioManager.onPause(() => {
            this.changePlayState(false);
        });
        this.audioManager.onStop(() => {
            this.changePlayState(false);
        });
        //监听音乐实时播放进度.
        this.audioManager.onTimeUpdate(() => {
            // console.log('总时长:' + this.audioManager.duration);
            // console.log('当前时间:' + this.audioManager.currentTime);
            const currentTime = moment(this.audioManager.currentTime * 1000).format('mm:ss');
            const ratio = this.audioManager.currentTime / this.audioManager.duration * 100 + '%';
            this.setData({currentTime, ratio});
        });
        //监听音乐播放结束
        this.audioManager.onEnded(() => {
            this.setData({ratio: '0%'});
            this.handleSwitch(null, 'next');
        });
    },

    changePlayState(isPlay) {
        this.setData({isPlay});
        app.globalData.isMusicPlay = isPlay;
    },

    //切换歌曲
    handleSwitch(e, type) {
        if (!type) {
            type = e.currentTarget.dataset.type;
        }

        //订阅：获取从每日推荐页面传递过来的songID----订阅操作放到这里，需要用完即删.
        // this.token = PubSub.subscribe('musicId', (msg, data) => {
        //     this.songID = data.songID;
        //     this.getSong();
        //     if (this.data.isPlay) {
        //         this.musicControll(true);
        //     }
        //     //用完即删，否则musicId对应的回调函数越来越多，回调函数会执行多次.
        //     PubSub.unsubscribe('musicId');
        // });

        //发布：通知每日推荐列表页我需要的是上一曲还是下一曲的songID
        PubSub.publish('music', {type, songID: this.songID});
        this.musicLink = null; //切换歌曲时必须置空
        this.musicControll(false); //切换时先暂停播放的歌曲
    },

    onUnload() {
        if (this.token) {
            PubSub.unsubscribe(this.token);
        }
    }
});
